package org.skatiger.jrove.component.foreach;

import java.util.Iterator;

public class ForeachStatusIteratorImpl implements ForeachStatusIterator {
    /**
     * 
     */
    private static final long serialVersionUID = 9121401863299085234L;
    private final Iterator<?> itr;
    private int begin = 0;
    private int end = Integer.MAX_VALUE;
    private int step = 1;
    private int index = 0;
    private boolean first = true;
    private ForeachStatus status;

    public ForeachStatusIteratorImpl(Iterator<?> iterator, Integer begin,
            Integer end, Integer step) {
        this.itr = iterator;
        if (begin != null) {
            this.begin = begin;
        }
        if (end != null) {
            this.end = end;
        }
        if (step != null) {
            this.step = step;
        }
        while (index < this.begin && this.hasNext()) {
            next();
            index++;
        }
    }

    public final Object next() {
        first = false;
        int mi = 1;
        while (mi < step && itr.hasNext()) {
            itr.next();
            mi++;
            index++;
        }
        index++;
        status = null;
        return itr.next();
    }

    public ForeachStatus getStatus() {
        if (status == null) {
            status = new ForeachStatus(first, !itr.hasNext(), index, begin,
                    end, step);
        }
        return status;
    }

    public void remove() {
        throw new UnsupportedOperationException("unsupported");
    }

    public boolean hasNext() {
        return itr.hasNext();
    }
}
